using UnityEngine;
using UnityEngine.UI;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using DG.Tweening;
using System.Collections;
using System.Collections.Generic;

public class DialougePanel : UIState
{
    [SerializeField] private Transform dialougeGroup;
    [SerializeField] private Image IconImage;
    [SerializeField] private Text NameText;
    [SerializeField] private Text dialougeText;
    [SerializeField] private Button nextNodeButton;

    [Header("Select Part")]
    [SerializeField] private Transform selectGroup;
    [SerializeField] private Button selectButton;

    private DialougeData currentDialougeData;
    private AudioSource audioSource;
    private Animator animator;



    protected override void Awake()
    { 
        base.Awake();
        animator = GetComponent<Animator>();
        audioSource = gameObject.AddComponent<AudioSource>();
        nextNodeButton.onClick.AddListener(()=>
        {

            if (currentDialougeData.IsOver)
            {
                EventManager.instance.GetEvent(currentDialougeData.Event).Apply();

                animator.SetTrigger("Exit");
            }
            else
            {
                OnNextNodeButtonClicked(DialouageManager.instance.GetData(currentDialougeData.NextNote));
            }
        });
    }

    private void OnNextNodeButtonClicked(DialougeData data)
    {
        if (data == null) // 处理选项
        {
            ShowSelectOptions();
        }
        else
        {
    
            ShowDialogue(data);
        }
    }

    private void ShowSelectOptions()
    {
        Debug.Log("选项部分");
        dialougeGroup.gameObject.SetActive(false);
        selectGroup.gameObject.SetActive(true);
        ClearSelectGroup();

        foreach (var item in currentDialougeData.DialogueOption)
        {
            var optionData = DialouageManager.instance.GetData(item);
            if (optionData == null)
            {
                Debug.LogError("不存在选择数据");
                continue;
            }
            CreateSelectButton(optionData);
        }
    }

    private void CreateSelectButton(DialougeData optionData)
    {
        var clone = Instantiate(selectButton, selectGroup, false);
        clone.GetComponentInChildren<Text>().text = optionData.Description;
        clone.GetComponent<Button>().onClick.AddListener(() =>
        {
            Debug.Log("选择项是"+optionData.NextNote);
            if (optionData.IsOver)
            {
                selectGroup.gameObject.SetActive(false);
                EventManager.instance.GetEvent(optionData.Event).Apply();
                animator.SetTrigger("Exit");

            }
            else
            {
                OnNextNodeButtonClicked(DialouageManager.instance.GetData(optionData.NextNote));
            }

        });
    }

    private void ClearSelectGroup()
    {
        foreach (Transform t in selectGroup)
        {
            Destroy(t.gameObject);
        }
    }

    private void ShowDialogue(DialougeData dialougeData)
    {
        if (dialougeData == null) return;
        dialougeGroup.gameObject.SetActive(true);
        selectGroup.gameObject.SetActive(false);


        currentDialougeData = dialougeData;
        nextNodeButton.gameObject.SetActive(false);
        audioSource.Stop();
        LoadIcon(dialougeData);
    }

    private void LoadIcon(DialougeData dialougeData)
    {
        Addressables.LoadAssetAsync<Sprite>(dialougeData.IconPath).Completed += handle =>
        {
            if (handle.Status == AsyncOperationStatus.Succeeded)
            {
                IconImage.sprite = handle.Result;
                NameText.text = dialougeData.Name;
                LoadAndPlayAudio(dialougeData);
            }
            else
            {
                Debug.LogError("Failed to load image: " + handle.OperationException);
            }
        };
    }

    private void LoadAndPlayAudio(DialougeData dialougeData)
    {
        Addressables.LoadAssetAsync<AudioClip>(dialougeData.AudioPath).Completed += handle =>
        {
            if (handle.Status == AsyncOperationStatus.Succeeded)
            {
                audioSource.clip = handle.Result;
                audioSource.Play();
                StartCoroutine(DisplayDialogue(dialougeData));
                StartCoroutine(WaitForAudioAndShowButton());
            }
            else
            {
                Debug.LogError("Failed to load audio: " + handle.OperationException);
                StartCoroutine(DisplayDialogue(dialougeData));
            }
        };
    }

    private IEnumerator WaitForAudioAndShowButton()
    {
        while (audioSource.isPlaying)
        {
            yield return null;
        }

        nextNodeButton.gameObject.SetActive(true);
        nextNodeButton.GetComponentInChildren<Text>().text = currentDialougeData.IsOver ? "完成" : "下一句";
    }

    private IEnumerator DisplayDialogue(DialougeData dialougeData)
    {
        dialougeText.text = "";
        yield return dialougeText.DOText(dialougeData.Description, dialougeData.Duration).WaitForCompletion();
    }

    public void AnimatorEnterEvent()
    {
        ShowDialogue(currentDialougeData);
    }
    public void AnimatorExitEvent()
    {
        GameStateManager.instance.SwitchPlay();
    }

    public void StartDialouage(DialougeData dialougeData)
    {
        animator.SetTrigger("Enter");
        currentDialougeData = dialougeData;
    }

    public override void SetData(Dictionary<string, object> data)
    {
        Debug.Log("对话面板接受到数据");
        if (data.ContainsKey("Dialouge") && data["Dialouge"] is DialougeData dialougeData)
        {
            Debug.Log(dialougeData.Name);

            StartDialouage(dialougeData);
        }
    }

    public override void Exit()
    {
        base.Exit();
    }

    //private void Update()
    //{
    //    if (Input.GetKeyDown(KeyCode.Escape))
    //    {
    //        StartDialouage(DialouageManager.instance.GetData(0));
    //    }
    //}
}
